<?php

namespace app\admin\controller\mycurrency\agent;

use app\common\controller\Backend;
use app\common\model\Area;
use app\common\model\mycurrency\AgentInformation;
use app\common\model\mycurrency\Agent as agent_model;
use app\common\model\mycurrency\AgentProfit;
use app\common\model\mycurrency\MerchantStaff;
use app\common\model\User;
use fast\Tree;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 代理商管理
 *
 * @icon fa fa-circle-o
 */
class Agent extends Backend
{

    /**
     * Agent模型对象
     * @var \app\admin\model\mycurrency\agent\Agent
     */
    protected $model = null;
    protected $categorylist = [];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\mycurrency\agent\Agent;

        $tree = Tree::instance();
        $tree->init(collection($this->model->order('id desc')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata = [0 => ['type' => 'all', 'name' => __('None')]];
        foreach ($this->categorylist as $k => $v) {
            $categorydata[$v['id']] = $v;
        }

        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("isidentityList", $this->model->getIsIdentityList());
        $this->view->assign("levelList", $this->model->getLevelList());
        $this->view->assign("roletypeList", $this->model->getRoleTyopeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $search = $this->request->request("search");
            $type = $this->request->request("type");

            //构造父类select列表选项数据
            $list = [];

            foreach ($this->categorylist as $k => $v) {
                $this->categorylist[$k]['agencyregion'] = Area::get($v['agency_region_id']);
                $this->categorylist[$k]['user'] = User::get($v['user_id']);
                if ($search) {
                    if ($v['type'] == $type && stripos($v['name'], $search) !== false || stripos($v['nickname'], $search) !== false) {
                        if ($type == "all" || $type == null) {
                            $list = $this->categorylist;
                        } else {
                            $list[] = $v;
                        }
                    }
                } else {
                    if ($type == "all" || $type == null) {
                        $list = $this->categorylist;
                    } elseif ($v['type'] == $type) {
                        $list[] = $v;
                    }
                }

            }

            $total = count($list);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        $admin = $this->request->post('admin/a');

        if($params['role_type'] == agent_model::ROLE_TYPE_DAILI){//如果是区域代理
            //将代理的省市区字符串转换成 对应的地区id
            $area_key = ['province_id','city_id','area_id'];
            $area_str = explode('/',$params['city']);
            $area_all = ['province_id' => null,'city_id' => null,'area_id' => null];//代理地区所属省市区id
            $agency_region_id = null;//代理地区id【省id or 市id or 区县id】
            for($i = 1;$i <= $params['level'];$i++){
                $area_all[$area_key[$i - 1]] = Area::where(['name' => $area_str[$i-1]])->value('id');
                if($i == $params['level']){
                    $agency_region_id = Area::where(['name' => $area_str[$i-1]])->value('id');
                }
            }
            $params['province_id'] = $area_all['province_id'];
            $params['city_id'] = $area_all['city_id'];
            $params['area_id'] = $area_all['area_id'];
            $params['agency_region_id'] = $agency_region_id;
        }

        $result = false;
        Db::startTrans();
        try {
            $result = agent_model::agentAdd($params,$admin,0);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $information = AgentInformation::where(['agent_id' => $ids])->find();
            $this->view->assign('information', $information);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        $admin = $this->request->post('admin/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $result = agent_model::agentUpdate($params,$ids);
            if($result == true){
                if ($admin['password'] != null){
                    $where = [];
                    if ($row->role_type == \app\common\model\mycurrency\Agent::ROLE_TYPE_DAILI){
                        $where['agent_id'] = $row->id;
                    }elseif ($row->role_type == \app\common\model\mycurrency\Agent::ROLE_TYPE_YEWUYUAN){
                        $where['business_agent_id'] = $row->id;
                    }
                    $staff = MerchantStaff::where($where)->find();
                    if ($staff){
                        $password = md5(md5($admin['password']) . $staff->salt);
                        $staff->password = $password;
                        $staff->save();
                    }
                }
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

}
